package com.example.lcode.list;

public class Question24 {

    public static class ListNode {
         int val;
         ListNode next;
         ListNode() {}
         ListNode(int val) { this.val = val; }
         ListNode(int val, ListNode next) { this.val = val; this.next = next; }
     }

    public ListNode swapPairs(ListNode head) {
        ListNode headNode = null;
        ListNode first = head;
        if (first == null || first.next == null) {
            return head;
        }
        ListNode second = head.next;
        ListNode lastSecond = null;
        while (first!= null && second != null) {
            ListNode slow = first;
            ListNode fast = second;
            first = first.next.next;
            if (first != null) {
                second = first.next;
            }
            slow.next = fast.next;
            if (lastSecond == null) {
                lastSecond = slow;
                fast.next = slow;
                headNode = fast;
            } else {
                fast.next = slow;
                lastSecond.next = fast;
                lastSecond = slow;
            }
        }
        return headNode;
    }

    public static void main(String[] args) {
        ListNode listNode1 = new ListNode(1);
        ListNode listNode2 = new ListNode(2);
        ListNode listNode3 = new ListNode(3);
        ListNode listNode4 = new ListNode(4);
        listNode1.next = listNode2;
        listNode2.next = listNode3;
        listNode3.next = listNode4;
        Question24 question24 = new Question24();
        question24.swapPairs(listNode1);
    }
}
